package com.admin.utils.jwt;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;
import java.util.Map;
import java.util.function.Function;

@Slf4j
public class JwtUtil {
	// 令牌自定义标识
	public static String header = "Authorization";
	public static  String bearer="Bearer";

	// 令牌秘钥
	private static String secret = "abcdefghijklmnopqrstuvwxyz";

	// 令牌有效期 1小时
	private static long EXPIRATION = 3600L;
	//记住我的 时长7天
	private static long EXPIRATION_REMEMBER = 604800L;


	public static String getToken(Map<String, Object> claims, Boolean remenber) {
		long expireTime = remenber ? EXPIRATION_REMEMBER : EXPIRATION;

		return Jwts.builder()
				.setClaims(claims)
				.setSubject(claims.get("name").toString())
				//设置失效时间
				.setExpiration(new Date(System.currentTimeMillis() + expireTime * 1000))
				.signWith(SignatureAlgorithm.HS512, secret)
				.compact();

	}


	private static Boolean isTokenExpired(String token) {
		Date expiration = getExpirationDateFromToken(token);
		return expiration.before(new Date());
	}

	public static Date getExpirationDateFromToken(String token) {
		return getClaimFromToken(token, Claims::getExpiration);
	}

	public static String getUserNameFromToken(String token) {
		return getClaimFromToken(token, Claims::getSubject);
	}

	public static Object getUserIdFromToken(String token) {
		Claims claims = getClaimsFromToken(token);
		return claims.get("id");
	}

	public static <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
		Claims claims = getClaimsFromToken(token);
		return claimsResolver.apply(claims);
	}

	private static Claims getClaimsFromToken(String token) {
		return Jwts.parser()
				.setSigningKey(secret)
				.parseClaimsJws(token)
				.getBody();
	}

	public static String refreshToken(Map<String, Object> claims, Boolean remenber) {
		long expireTime = remenber ? EXPIRATION_REMEMBER : EXPIRATION;
		return null;

	}

	/**
	 * 验证用户token是否有效
	 */
	public static boolean validateToken(String token, String name){
		String username = getUserNameFromToken(token);
		return username.equals(name)&&!isTokenExpried(token);
	}

	/**
	 * 判断token是否有效
	 * @param token
	 * @return
	 */
	public static boolean isTokenExpried(String token){
		Date expiredDate = getExpirationDateFromToken(token);
		return expiredDate.before(new Date());
	}


	/**
	 * 判断token是否可以被刷新
	 * @param token
	 * @return
	 */
	public static boolean canRefresh(String token){
		return !isTokenExpried(token);
	}
	/**
	 * 刷新token有效时间
	 * @param token
	 * @return
	 */
	public static  String refeshToken(String token,Boolean remenber){
		Claims claims = getClaimsFromToken(token);
		claims.put("create", new Date());
		return getToken(claims,remenber);
	}

}


